package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.TradeTrademarkCategoryUserSpuOrderBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.function.DimAsyncFunction;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2022/5/9 14:29
 */
public class Dws_09_DwsTradeTrademarkCategoryUserSpuOrderWindowApp extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_09_DwsTradeTrademarkCategoryUserSpuOrderWindowApp().init(
            "Dws_9_DwsTradeTrademarkCategoryUserSpuOrderWindowApp",
            4009,
            1,
            "Dws_9_DwsTradeTrademarkCategoryUserSpuOrderWindowApp",
            "Dws_9_DwsTradeTrademarkCategoryUserSpuOrderWindowApp",
            "dwd_trade_order_detail"
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        
        
        // 1. 按照order_detail_id去重
        SingleOutputStreamOperator<JSONObject> disinctedStream = distinctByOrderDetailId(stream);
        
        // 2. 转换数据结构
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> beanStream = parseToBean(disinctedStream);
        
        // 3. 补充 spu_id tm_id category3_id 维度
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> beanStreamWithSpuId = addSkuAndSpuDim(beanStream);
        
        // 4. 开窗聚合
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> resultStreamWithoutDim = windowAndAgg(beanStreamWithSpuId);
        // 5. 补充其他维度相关信息
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> streamWithAllDim = addOtherDim(resultStreamWithoutDim);
    
        // 6. 写出到ClickHouse中
        writeToClickHouse(streamWithAllDim);
        
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> streamWithAllDim) {
        streamWithAllDim.addSink(FlinkSinkUtil.getClickHouseSink(
            Constant.CLICKHOUSE_DB,
            "dws_trade_trademark_category_user_spu_order_window",
            TradeTrademarkCategoryUserSpuOrderBean.class
        ));
    }
    
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> addOtherDim(
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> stream) {
        
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> streamWithSpu = AsyncDataStream
            .unorderedWait(
                stream,
                new DimAsyncFunction<TradeTrademarkCategoryUserSpuOrderBean>() {
                    
                    protected void addDim(JSONObject dim,
                                          TradeTrademarkCategoryUserSpuOrderBean input) throws Exception {
                        input.setSpuName(dim.getString("SPU_NAME"));
                    }
                    
                    @Override
                    protected String getId(TradeTrademarkCategoryUserSpuOrderBean input) {
                        return input.getSpuId();
                    }
                    
                    @Override
                    protected String getTableName() {
                        return "gmall2022.dim_spu_info";
                    }
                },
                60 * 1000,
                TimeUnit.SECONDS
            );
        
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> streamWithTm = AsyncDataStream
            .unorderedWait(
                streamWithSpu,
                new DimAsyncFunction<TradeTrademarkCategoryUserSpuOrderBean>() {
                    
                    protected void addDim(JSONObject dim,
                                          TradeTrademarkCategoryUserSpuOrderBean input) throws Exception {
                        input.setTrademarkName(dim.getString("TM_NAME"));
                    }
                    
                    @Override
                    protected String getId(TradeTrademarkCategoryUserSpuOrderBean input) {
                        return input.getTrademarkId();
                    }
                    
                    @Override
                    protected String getTableName() {
                        return "gmall2022.dim_base_trademark";
                    }
                },
                60 * 1000,
                TimeUnit.SECONDS
            );
        
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> streamWithC3 = AsyncDataStream
            .unorderedWait(
                streamWithTm,
                new DimAsyncFunction<TradeTrademarkCategoryUserSpuOrderBean>() {
                    
                    protected void addDim(JSONObject dim,
                                          TradeTrademarkCategoryUserSpuOrderBean input) throws Exception {
                        input.setCategory3Name(dim.getString("NAME"));
                        
                        input.setCategory2Id(dim.getString("CATEGORY2_ID"));
                    }
                    
                    @Override
                    protected String getId(TradeTrademarkCategoryUserSpuOrderBean input) {
                        return input.getCategory3Id();
                    }
                    
                    @Override
                    protected String getTableName() {
                        return "gmall2022.dim_base_category3";
                    }
                },
                60 * 1000,
                TimeUnit.SECONDS
            );
        
        
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> streamWithC2 = AsyncDataStream
            .unorderedWait(
                streamWithC3,
                new DimAsyncFunction<TradeTrademarkCategoryUserSpuOrderBean>() {
                    
                    protected void addDim(JSONObject dim,
                                          TradeTrademarkCategoryUserSpuOrderBean input) throws Exception {
                        input.setCategory2Name(dim.getString("NAME"));
                        
                        input.setCategory1Id(dim.getString("CATEGORY1_ID"));
                    }
                    
                    @Override
                    protected String getId(TradeTrademarkCategoryUserSpuOrderBean input) {
                        return input.getCategory2Id();
                    }
                    
                    @Override
                    protected String getTableName() {
                        return "gmall2022.dim_base_category2";
                    }
                },
                60 * 1000,
                TimeUnit.SECONDS
            );
        
        
        return AsyncDataStream
            .unorderedWait(
                streamWithC2,
                new DimAsyncFunction<TradeTrademarkCategoryUserSpuOrderBean>() {
                    
                    protected void addDim(JSONObject dim,
                                          TradeTrademarkCategoryUserSpuOrderBean input) throws Exception {
                        input.setCategory1Name(dim.getString("NAME"));
                        
                    }
                    
                    @Override
                    protected String getId(TradeTrademarkCategoryUserSpuOrderBean input) {
                        return input.getCategory1Id();
                    }
                    
                    @Override
                    protected String getTableName() {
                        return "gmall2022.dim_base_category1";
                    }
                },
                60 * 1000,
                TimeUnit.SECONDS
            );
    }
    
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> addSkuAndSpuDim(
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> beanStream) {
        
        return AsyncDataStream
            .unorderedWait(
                beanStream,
                new DimAsyncFunction<TradeTrademarkCategoryUserSpuOrderBean>() {
                    
                    @Override
                    protected void addDim(JSONObject skuInfo,
                                          TradeTrademarkCategoryUserSpuOrderBean input) throws Exception {
                        // 等聚合完之后再去查找其他维度
                        input.setSpuId(skuInfo.getString("SPU_ID"));
                        input.setTrademarkId(skuInfo.getString("TM_ID"));
                        input.setCategory3Id(skuInfo.getString("CATEGORY3_ID"));
                    }
                    
                    @Override
                    protected String getId(TradeTrademarkCategoryUserSpuOrderBean input) {
                        return input.getSkuId();
                    }
                    
                    @Override
                    protected String getTableName() {
                        return "gmall2022.dim_sku_info";
                    }
                },
                60 * 1000,
                TimeUnit.SECONDS
            );
        
        
    }
    
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> windowAndAgg(
        SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeTrademarkCategoryUserSpuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .keyBy(bean -> bean.getSpuId() + "_" + bean.getUserId())
            .window(TumblingEventTimeWindows.of(Time.seconds(10)))
            .reduce(
                new ReduceFunction<TradeTrademarkCategoryUserSpuOrderBean>() {
                    @Override
                    public TradeTrademarkCategoryUserSpuOrderBean reduce(TradeTrademarkCategoryUserSpuOrderBean bean1,
                                                                         TradeTrademarkCategoryUserSpuOrderBean bean2) throws Exception {
                        bean1.getOrderIdSet().addAll(bean2.getOrderIdSet());
                        bean1.setOrderAmount(bean1.getOrderAmount() + bean2.getOrderAmount());
                        return bean1;
                    }
                },
                new ProcessWindowFunction<TradeTrademarkCategoryUserSpuOrderBean, TradeTrademarkCategoryUserSpuOrderBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<TradeTrademarkCategoryUserSpuOrderBean> elements,
                                        Collector<TradeTrademarkCategoryUserSpuOrderBean> out) throws Exception {
                        TradeTrademarkCategoryUserSpuOrderBean bean = elements.iterator().next();
                        
                        bean.setOrderCount((long) bean.getOrderIdSet().size());
                        bean.setStt(DateFormatUtil.toYmdHms(ctx.window().getStart()));
                        bean.setEdt(DateFormatUtil.toYmdHms(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeTrademarkCategoryUserSpuOrderBean> parseToBean(
        SingleOutputStreamOperator<JSONObject> disinctedStream) {
        return disinctedStream
            .map(obj -> TradeTrademarkCategoryUserSpuOrderBean.builder()
                .userId(obj.getString("user_id"))
                .skuId(obj.getString("sku_id"))
                .orderAmount(obj.getDouble("split_total_amount"))
                .orderIdSet(new HashSet<>(Collections.singleton(obj.getString("order_id"))))
                .ts(obj.getLong("ts") * 1000)
                .build());
    }
    
    private SingleOutputStreamOperator<JSONObject> distinctByOrderDetailId(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getLong("id"))
            .process(new KeyedProcessFunction<Long, JSONObject, JSONObject>() {
                // 存储数据最全的状态
                private ValueState<JSONObject> lastDataState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastDataState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("lastDataState", JSONObject.class));
                }
                
                @Override
                public void processElement(JSONObject data,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject lastData = lastDataState.value();
                    if (lastData == null) {
                        // 把数据存入到状态中, 并定义定时器
                        lastDataState.update(data);
                        
                        ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000);
                    } else {
                        // 2022-05-08 15:30:56.723Z   row_op_ts":"2022-05-08 15:30:56.72Z
                        String currentTime = data.getString("row_op_ts");
                        String lastTime = lastData.getString("row_op_ts");
                        // 新数据的生成时间是否 大于 状态中的数据的生成时间
                        boolean isGreatOrEqual = AtguiguUtil.compareLTZ(currentTime, lastTime);
                        if (isGreatOrEqual) {
                            // 更新状态
                            lastDataState.update(data);
                        }
                    }
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<JSONObject> out) throws Exception {
                    out.collect(lastDataState.value());
                }
            });
    }
    
    
}
